var path = require('path');

var request = require('request-promise');
var log4js = require(path.resolve(__dirname, '../config/logger'));
var logger = log4js.getLogger('status');
var DbCommon = require('./db');
//const pulishUrl = 'http://192.168.9.46:37000/call_taf?action=publishNews';
const pulishUrl = 'http://192.168.9.46:52479/?s=dbsync&f=saveNews&req=SaveNewsReq&rsp=SaveNewsRsp';
//const pulishUrl = 'http://comm.wedengta.com/?s=dbsync&f=saveNews&req=SaveNewsReq&rsp=SaveNewsRsp';
//const pulishUrl = 'http://apiproxy.wedengta.com/call_taf?action=publishNews';
const Publish = {
  post: function (params, newsId, url) {
    return new Promise(function (resolve, reject) {
      let options = {
        method: 'POST',
        uri: url || pulishUrl,
        body: params,
        json: true
      }
      logger.info(params);
      request(options).then(function (res) {
        logger.info(res);
        if (res.ret == 0) {
          logger.info(params.stNewsDesc.sTitle + ' publish success');
          DbCommon.executeMysql({
            sql: 'update news set status = 2 where id = ?',
            params: [newsId]
          }).then(function () {
            logger.info('news: ' + newsId + ' publish success');
          }).catch(function (err) {
            logger.info(err);
          })
          resolve();
        } else {
          logger.info(params.stNewsDesc.sTitle + ' publish error');
          reject(new Error(res.msg || (params.stNewsDesc.sTitle + ' publish error')));
        }
      }).catch(function (error) {
        reject(error);
      })
    })
  }
}

module.exports = Publish;